package com.example.audiostreaming.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.example.audiostreaming.R;

/**
 * ImageView图像视图自定义控件
 * 正在加载图像视图
 */
@SuppressLint("AppCompatCustomView")
public class ViewLoadingView extends ImageView {


    private int rotateDegree = 0;//旋转角度

    private boolean mNeedRotate = false;//是否需要旋转


    public ViewLoadingView(Context context) {
        this(context, null);//确保唯一入口
    }

    public ViewLoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);//确保唯一入口
    }


    public ViewLoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setImageResource(R.mipmap.loading_icon); //设置图标
    }

    /**
     * /绑定到窗口的时候
     */
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mNeedRotate = true;
        post(new Runnable() {
            @Override
            public void run() {
                rotateDegree += 30;
                rotateDegree = rotateDegree <= 360 ? rotateDegree : 0;
                invalidate();
                //是否继续旋转
                if (mNeedRotate) {
                    postDelayed(this, 100);//发布延迟
                }
            }
        });
    }

    /**
     *  //从窗口解绑的时候
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mNeedRotate = false;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        /**
         * 第一个参数是旋转角度
         * 第二个参数是旋转的x坐标
         * 第三个参数是旋转的y坐标
         */
        canvas.rotate(rotateDegree, getWidth() / 2, getHeight() / 2); //画布旋转
        super.onDraw(canvas);
    }
}
